package com.hand.wfive.loginAndVip.ui

import android.text.TextUtils
import com.hand.wfive.ad.AdConfig
import com.hand.wfive.loginAndVip.ApiConfig
import com.hand.wfive.loginAndVip.LoginConfig
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.loginAndVip.model.ActivityConfigModel
import com.hand.wfive.loginAndVip.model.CouponModel
import com.hand.wfive.loginAndVip.model.VipActivityModel
import com.hand.wfive.util.SharedPreferencesUtils
import com.rxjava.rxlife.RxLife

import org.litepal.LitePal
import rxhttp.wrapper.param.RxHttp

/**
 * 会员页优惠券活动等配置
 * 获取活动数据，优惠券倒计时等本地化处理
 * @see BasePayActivity 无活动优惠券直接继承该类
 */
abstract class BaseVipActivity : BasePayActivity() {

    private var mQueryVipPriceByKey = LoginConfig.AppId
    protected var mVipActivityModel = VipActivityModel()
    protected var mActivityConfigModel = ActivityConfigModel() //会员活动配置
    private var mVipCouponList: ArrayList<CouponModel>? = null //优惠券列表
    private var mCouponLocalData: MutableList<CouponModel>? = null //优惠券列表本地缓存（优惠券到期后需要重新领取）
    protected var mCurrentCouponModel: CouponModel? = null //当前选中的优惠券

    private var mActivityStartTime = 0L//活动开始计时的时间

    override fun initViewData() {
        isHasCoupon = mSpUtils.getValue(SharedPreferencesUtils.KEY_IS_HAS_COUPON, false) || AdConfig.isHuawei()
        mActivityStartTime = mSpUtils.getValue(SharedPreferencesUtils.KEY_ACTIVITY_START_TIME, 0L)
        mCouponLocalData = LitePal.findAll(CouponModel::class.java)

        if (!isHasCoupon) {
            LitePal.deleteAll(CouponModel::class.java)
        }
        queryActivityConfig()
    }

    /**
     * 刷新活动数据（如倒计时结束需要刷新）
     */
    protected fun refreshData() {
        queryActivityConfig()
        getVipPriceConfig(false)
    }

    /**
     * 选中的优惠券改变，进行对应的ui刷新
     */
    protected abstract fun onUpdateCurrentCoupon(coupon: CouponModel?)

    private fun queryActivityConfig() {
//        showLoading("请稍后...")
        RxHttp.postForm(ApiConfig.queryActivityConfig)
            .add("key", mQueryVipPriceByKey)
            .add("userId", UserManager.getInstance().userId)
            .add("isNewOld", 1)
            .asClass(VipActivityModel::class.java)
            .to(RxLife.toMain(this))
            .subscribe({ apiModel ->
                if (apiModel.code == ApiConfig.SUCCESSCODE) {
                    mVipActivityModel = apiModel
                    mVipCouponList = apiModel.couponList as ArrayList<CouponModel>?
                    mActivityConfigModel = apiModel.obj ?: ActivityConfigModel()
                    if ((mVipCouponList?.size ?: 0) > 0) {
                        //有优惠券
                        if (AdConfig.isHuawei()) {
                            updateCouponStatus()
                        }
                        initVipCouponList()
                        updateCurrentCoupon()
                    }
                    if (mActivityStartTime <= 0 && mActivityConfigModel.isNeedSaveStartTime()) {
                        saveActivityStartTime(SharedPreferencesUtils.KEY_ACTIVITY_START_TIME)
                    }
                    onNetSuccess(REQ_ID_VIP_ACTIVITY)
                }
            }, {
                onNetError(REQ_ID_VIP_ACTIVITY)
            })
    }

    /**
     * 如果优惠券领取，则获取优惠券的倒计时的开始时间
     */
    private fun initVipCouponList() {
        if (isHasCoupon) {
            mVipCouponList?.forEachIndexed { _, couponModel ->
                mCouponLocalData?.forEach {
                    if (TextUtils.equals(it.vipType, couponModel.vipType)) {
                        couponModel.couponStartTime = it.couponStartTime
                    }
                }
                couponModel.saveOrUpdate("viptype=?", couponModel.vipType)
            }
            mCouponLocalData?.forEach {
                var isHasData = false
                mVipCouponList?.forEachIndexed { _, couponModel ->
                    if (TextUtils.equals(it.vipType, couponModel.vipType)) {
                        isHasData = true
                    }
                }
                if (!isHasData) {
                    it.delete()
                }
            }

            mCouponLocalData = LitePal.findAll(CouponModel::class.java)
        }
    }

    /**
     * 保存活动计时开始时间戳
     */
    private fun saveActivityStartTime(spKey: String) {
        mSpUtils.putValue(spKey, System.currentTimeMillis())
    }

    /**
     * 保存优惠券计时开始时间戳
     */
    private fun saveCouponStartTime() {
        mVipCouponList?.forEach {
            it.couponStartTime = System.currentTimeMillis()
            it.saveOrUpdate("viptype=?", it.vipType)
        }
        mCouponLocalData = LitePal.findAll(CouponModel::class.java)
    }

    /**
     * 重新领取优惠券(只有过期优惠券会重新领取)
     */
    private fun retrieveCoupleList() {
        mVipCouponList?.forEach {
            if (it.couponStartTime < 1000) {
                it.couponStartTime = System.currentTimeMillis()
                it.saveOrUpdate("viptype=?", it.vipType)
            }
        }
        mCouponLocalData?.forEach {
            if (it.couponStartTime < 1000) {
                it.couponStartTime = System.currentTimeMillis()
                it.saveOrUpdate("viptype=?", it.vipType)
            }
        }
    }

    /**
     * 更新当前选中的优惠券
     */
    override fun updateCurrentCoupon() {
        super.updateCurrentCoupon()
        mCurrentCouponModel = getSelectCoupon()
        onUpdateCurrentCoupon(mCurrentCouponModel)
    }

    /**
     * 更新优惠券的领取状态为：已领取 ,并且刷新ui
     */
    protected fun updateCouponStatus() {
        mSpUtils.putValue(SharedPreferencesUtils.KEY_IS_HAS_COUPON, true)
        if (!isHasCoupon) { //记录领取优惠券的时间，用于计算剩余倒计时时长（优惠券领取，倒计时开始）
            saveCouponStartTime()
        } else {
            retrieveCoupleList()
        }
        isHasCoupon = true
        if (mCurVipModel != null) {
            updateCurrentCoupon()
        }
    }

    /**
     * 删除过期优惠券（并不真正删除只是设置过期）
     */
    override fun deleteCurrentCoupon() {
        super.deleteCurrentCoupon()
        mVipCouponList?.forEachIndexed { _, couponModel ->
            if (TextUtils.equals(mCurVipModel?.productKey, couponModel.vipType)) {
                couponModel.couponStartTime = 0L
            }
        }
        mCouponLocalData?.forEach {
            if (TextUtils.equals(mCurVipModel?.productKey, it.vipType)) {
                it.couponStartTime = 0L
                it.saveOrUpdate("viptype=?", it.vipType)
            }
        }
        onUpdateCurrentCoupon(mCurrentCouponModel)
    }

    /**
     * 删除所有的优惠券（并不真正删除只是设置过期）
     */
    protected fun deleteAllCoupon() {
        mVipCouponList?.forEachIndexed { _, couponModel ->
            couponModel.couponStartTime = 0L
        }
        mCouponLocalData?.forEach {
            it.couponStartTime = 0L
            it.saveOrUpdate("viptype=?", it.vipType)
        }
        isHasCoupon = false
        mSpUtils.putValue(SharedPreferencesUtils.KEY_IS_HAS_COUPON, false)
        onUpdateCurrentCoupon(mCurrentCouponModel)
    }

    /**
     * 获取当前选中的优惠券
     */
    override fun getSelectCoupon(): CouponModel? {
        if (mVipCouponList == null) {
            return null
        }
        mVipCouponList?.forEachIndexed { _, couponModel ->
            //当前会员卡存在优惠券，并且优惠券没有过期
            if (TextUtils.equals(mCurVipModel?.productKey, couponModel.vipType) && couponModel.couponStartTime >= 0) {
                return couponModel
            }
        }
        return super.getSelectCoupon()
    }

    override fun getCurrentCouponModel(): CouponModel? {
        return mCurrentCouponModel
    }

}